package com.example.teemor.es_demo.controller;

import com.example.teemor.es_demo.dto.ApiResponse;
import com.example.teemor.es_demo.dto.PageResponse;
import com.example.teemor.es_demo.entity.ServiceLog;
import com.example.teemor.es_demo.entity.UserBehavior;
import com.example.teemor.es_demo.service.LogManagementService;
import com.example.teemor.es_demo.service.UserTrackingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 日志管理控制器
 * 提供日志查询和用户行为追踪的REST API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/logs")
@RequiredArgsConstructor
public class LogManagementController {
    
    private final LogManagementService logManagementService;
    private final UserTrackingService userTrackingService;
    
    /**
     * 分页查询服务日志
     * 
     * @param startTime 开始时间 (格式: yyyy-MM-dd HH:mm:ss)
     * @param endTime 结束时间 (格式: yyyy-MM-dd HH:mm:ss)
     * @param keyword 关键词搜索
     * @param level 日志级别 (DEBUG, INFO, WARN, ERROR)
     * @param page 页码 (从0开始)
     * @param size 每页大小
     * @return 分页结果
     */
    @GetMapping("/service")
    public ApiResponse<PageResponse<ServiceLog>> queryServiceLogs(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String level,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        try {
            PageResponse<ServiceLog> result = logManagementService.queryServiceLogs(
                startTime, endTime, keyword, level, page, size);
            
            return ApiResponse.success(result);
            
        } catch (Exception e) {
            log.error("查询服务日志失败", e);
            return ApiResponse.error("查询服务日志失败: " + e.getMessage());
        }
    }
    
    /**
     * 分页查询用户行为日志
     * 
     * @param startTime 开始时间 (格式: yyyy-MM-dd HH:mm:ss)
     * @param endTime 结束时间 (格式: yyyy-MM-dd HH:mm:ss)
     * @param keyword 关键词搜索
     * @param page 页码 (从0开始)
     * @param size 每页大小
     * @return 分页结果
     */
    @GetMapping("/behavior")
    public ApiResponse<PageResponse<UserBehavior>> queryUserBehaviors(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        try {
            PageResponse<UserBehavior> result = logManagementService.queryUserBehaviors(
                startTime, endTime, keyword, page, size);
            
            return ApiResponse.success(result);
            
        } catch (Exception e) {
            log.error("查询用户行为日志失败", e);
            return ApiResponse.error("查询用户行为日志失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取服务日志统计信息
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 统计信息
     */
    @GetMapping("/service/stats")
    public ApiResponse<LogManagementService.ServiceLogStats> getServiceLogStats(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        
        try {
            LogManagementService.ServiceLogStats stats = 
                logManagementService.getServiceLogStats(startTime, endTime);
            
            return ApiResponse.success(stats);
            
        } catch (Exception e) {
            log.error("获取服务日志统计信息失败", e);
            return ApiResponse.error("获取服务日志统计信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户行为日志统计信息
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 统计信息
     */
    @GetMapping("/behavior/stats")
    public ApiResponse<LogManagementService.UserBehaviorStats> getUserBehaviorStats(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        
        try {
            LogManagementService.UserBehaviorStats stats = 
                logManagementService.getUserBehaviorStats(startTime, endTime);
            
            return ApiResponse.success(stats);
            
        } catch (Exception e) {
            log.error("获取用户行为日志统计信息失败", e);
            return ApiResponse.error("获取用户行为日志统计信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 记录用户行为（通用接口）
     * 
     * @param request 埋点请求数据
     * @param httpRequest HTTP请求对象
     * @return 操作结果
     */
    @PostMapping("/track")
    public ApiResponse<String> trackUserBehavior(@RequestBody TrackingRequest request, 
                                                HttpServletRequest httpRequest) {
        
        try {
            userTrackingService.trackUserBehavior(
                request.getUserId(),
                request.getSessionId(),
                request.getEventType(),
                request.getPageUrl(),
                request.getEventData(),
                httpRequest
            );
            
            return ApiResponse.success("用户行为记录成功");
            
        } catch (Exception e) {
            log.error("记录用户行为失败", e);
            return ApiResponse.error("记录用户行为失败: " + e.getMessage());
        }
    }
    
    /**
     * 记录页面访问
     * 
     * @param request 页面访问请求数据
     * @param httpRequest HTTP请求对象
     * @return 操作结果
     */
    @PostMapping("/track/page-view")
    public ApiResponse<String> trackPageView(@RequestBody PageViewRequest request, 
                                           HttpServletRequest httpRequest) {
        
        try {
            userTrackingService.trackPageView(
                request.getUserId(),
                request.getSessionId(),
                request.getPageUrl(),
                request.getPageTitle(),
                httpRequest
            );
            
            return ApiResponse.success("页面访问记录成功");
            
        } catch (Exception e) {
            log.error("记录页面访问失败", e);
            return ApiResponse.error("记录页面访问失败: " + e.getMessage());
        }
    }
    
    /**
     * 记录按钮点击
     * 
     * @param request 按钮点击请求数据
     * @param httpRequest HTTP请求对象
     * @return 操作结果
     */
    @PostMapping("/track/button-click")
    public ApiResponse<String> trackButtonClick(@RequestBody ButtonClickRequest request, 
                                              HttpServletRequest httpRequest) {
        
        try {
            userTrackingService.trackButtonClick(
                request.getUserId(),
                request.getSessionId(),
                request.getPageUrl(),
                request.getButtonId(),
                request.getButtonText(),
                httpRequest
            );
            
            return ApiResponse.success("按钮点击记录成功");
            
        } catch (Exception e) {
            log.error("记录按钮点击失败", e);
            return ApiResponse.error("记录按钮点击失败: " + e.getMessage());
        }
    }
    
    /**
     * 记录表单提交
     * 
     * @param request 表单提交请求数据
     * @param httpRequest HTTP请求对象
     * @return 操作结果
     */
    @PostMapping("/track/form-submit")
    public ApiResponse<String> trackFormSubmit(@RequestBody FormSubmitRequest request, 
                                             HttpServletRequest httpRequest) {
        
        try {
            userTrackingService.trackFormSubmit(
                request.getUserId(),
                request.getSessionId(),
                request.getPageUrl(),
                request.getFormId(),
                request.getFormType(),
                httpRequest
            );
            
            return ApiResponse.success("表单提交记录成功");
            
        } catch (Exception e) {
            log.error("记录表单提交失败", e);
            return ApiResponse.error("记录表单提交失败: " + e.getMessage());
        }
    }
    
    // DTO类定义
    
    /**
     * 通用埋点请求
     */
    public static class TrackingRequest {
        private String userId;
        private String sessionId;
        private String eventType;
        private String pageUrl;
        private Map<String, Object> eventData;
        
        // Getters and Setters
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        public String getSessionId() { return sessionId; }
        public void setSessionId(String sessionId) { this.sessionId = sessionId; }
        public String getEventType() { return eventType; }
        public void setEventType(String eventType) { this.eventType = eventType; }
        public String getPageUrl() { return pageUrl; }
        public void setPageUrl(String pageUrl) { this.pageUrl = pageUrl; }
        public Map<String, Object> getEventData() { return eventData; }
        public void setEventData(Map<String, Object> eventData) { this.eventData = eventData; }
    }
    
    /**
     * 页面访问请求
     */
    public static class PageViewRequest {
        private String userId;
        private String sessionId;
        private String pageUrl;
        private String pageTitle;
        
        // Getters and Setters
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        public String getSessionId() { return sessionId; }
        public void setSessionId(String sessionId) { this.sessionId = sessionId; }
        public String getPageUrl() { return pageUrl; }
        public void setPageUrl(String pageUrl) { this.pageUrl = pageUrl; }
        public String getPageTitle() { return pageTitle; }
        public void setPageTitle(String pageTitle) { this.pageTitle = pageTitle; }
    }
    
    /**
     * 按钮点击请求
     */
    public static class ButtonClickRequest {
        private String userId;
        private String sessionId;
        private String pageUrl;
        private String buttonId;
        private String buttonText;
        
        // Getters and Setters
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        public String getSessionId() { return sessionId; }
        public void setSessionId(String sessionId) { this.sessionId = sessionId; }
        public String getPageUrl() { return pageUrl; }
        public void setPageUrl(String pageUrl) { this.pageUrl = pageUrl; }
        public String getButtonId() { return buttonId; }
        public void setButtonId(String buttonId) { this.buttonId = buttonId; }
        public String getButtonText() { return buttonText; }
        public void setButtonText(String buttonText) { this.buttonText = buttonText; }
    }
    
    /**
     * 表单提交请求
     */
    public static class FormSubmitRequest {
        private String userId;
        private String sessionId;
        private String pageUrl;
        private String formId;
        private String formType;
        
        // Getters and Setters
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        public String getSessionId() { return sessionId; }
        public void setSessionId(String sessionId) { this.sessionId = sessionId; }
        public String getPageUrl() { return pageUrl; }
        public void setPageUrl(String pageUrl) { this.pageUrl = pageUrl; }
        public String getFormId() { return formId; }
        public void setFormId(String formId) { this.formId = formId; }
        public String getFormType() { return formType; }
        public void setFormType(String formType) { this.formType = formType; }
    }
}